import json
import logging
import re
import pandas as pd
import requests
import config.globalVariable as gv
from datetime import datetime

log = logging.getLogger()
def getPlateData():
    '''
    获取开盘啦热点板块数据
    :return: DataFrame
    '''
    print('获取开盘啦热点板块数据')
    url = gv.kaipanlaApiAddress + '?Order=1&a=RealRankingInfo&st=20&apiv=w29&Type=1&c=ZhiShuRanking&PhoneOSNew=1&DeviceID=ffffffff-cf63-0494-0000-00004e79e45a&Index=0&ZSType=7&'
    headers = {
        'user-agent': 'Mozilla/5.0(Linux; Android 7.1.2; SM-G955N Build/NRD90M.G955NKSU1AQDC; wv)'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200:
        return None
    # 解析JSON数据
    data = json.loads(response.text)
    errcode = data.get('errcode')
    if errcode != '0':
        logging.warning('获取开盘啦热点板块数据错误 errorcode:'+errcode)
        return None
    plate_data_all = pd.DataFrame()
    # 遍历股票列表，提取数据
    for item in data.get('list'):
        # 涨幅格式
        zf = str(round(item[3], 2)) + '%'
        # 涨速格式
        #zs = str(round(item[4], 2)) + '%'
        # 主力净额
        zlje = str(round(item[6] / 100000000, 2)) + '亿'
        # 成交额
        #cje = str(round(item[5] / 100000000, 2)) + '亿'
        item_data = [
            item[0],
            item[1],
            item[2],
            zf,
            zlje,
        ]
        # 将数据转换成DataFrame类型
        data = pd.DataFrame(item_data).T
        dict = {0: '股票代码', 1: '板块', 2: '人气', 3: '涨幅', 4: '主力净额'}
        data.rename(columns=dict, inplace=True)
        plate_data_all = plate_data_all._append(data, ignore_index=True)
    # 返回DataFrame类型数据
    return plate_data_all

def getPlateSubData(num,plateID):
    '''
    获取板块下个股数据
    :return:DataFrom
    '''
    print('获取板块下个股数据')
    if num is None or len(num) == 0:
        num = str(20)
    if plateID is None:
        return None

    #https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=InterviewsByDate&st=51&c=ZhiShuRanking&PhoneOSNew=1&DeviceID=00000000-2de4-c43b-ffff-ffff99d603a9&DEnd=2023-12-29&Token=0&Index=0&DStart=2023-12-28&apiv=w28&Type=2&UserID=0&PlateID=801212&
    url = gv.kaipanlaApiAddress + '?Order=1&a=ZhiShuStockList_W8&st='+num+'&c=ZhiShuRanking&PhoneOSNew=1&old=1&DeviceID=00000000-2de4-c43b-ffff-ffff99d603a9&IsZZ=0&VerSion=5.13.0.0&Token=0&Index=0&apiv=w29&Type=6&UserID=0&PlateID='+plateID+'&'
    headers = {
        'user-agent': 'Mozilla/5.0(Linux; Android 7.1.2; SM-G955N Build/NRD90M.G955NKSU1AQDC; wv)'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200:
        return None
    # 解析JSON数据
    data = json.loads(response.text)
    errcode = data.get('errcode')
    if errcode != '0':
        logging.warning('获取开盘啦热点板块数据错误 errorcode:'+errcode)
        return None
    plate_data_all = pd.DataFrame()
    upNum = 0
    # 遍历股票列表，提取数据
    for item in data.get('list'):
        # 涨幅格式
        zf = str(round(item[6], 2)) + '%'
        # 主力净额
        zlje = str(round(item[13] / 10000, 2)) + '万'
        #涨停封单
        ztfd = item[28]
        if str(ztfd).find('-') != -1:
            item[28]= 0
        ztfd = str(round(item[28] / 100000000, 2)) + '亿'
        if item[28]>0:
            upNum+=1
        item_data = [
            item[0],
            item[1],
            item[5],
            zf,
            zlje,
            str(item[8])+'%',
            ztfd,
            item[4],
            item[24]+' '+item[39]+' '+item[23] + ' '+ item[2]
        ]
        # 将数据转换成DataFrame类型
        data = pd.DataFrame(item_data).T
        dict = {0: '股票代码', 1: '股票名称', 2: '价格', 3: '涨幅', 4: '主力净额',5: '换手Z',6: '涨停封单',7:'板块',8:'备注'}
        data.rename(columns=dict, inplace=True)
        plate_data_all = plate_data_all._append(data, ignore_index=True)
    return plate_data_all,upNum

def getLimitUpData():
    '''
    获取涨停数据
    :return: 涨停数据 map：{2023-12-29:[value]}
    '''
    #https://apphq.longhuvip.com/w1/api/index.php?a=GetPlateInfo&st=50&apiv=w29&c=DailyLimitResumption&PhoneOSNew=1&DeviceID=00000000-2de4-c43b-ffff-ffff99d603a9&Index=0&
    url = gv.kaipanlaApiAddress + '?a=GetPlateInfo&st=50&apiv=w29&c=DailyLimitResumption&PhoneOSNew=1&DeviceID=00000000-2de4-c43b-ffff-ffff99d603a9&Index=0&'
    headers = {
        'user-agent': 'Mozilla/5.0(Linux; Android 7.1.2; SM-G955N Build/NRD90M.G955NKSU1AQDC; wv)'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200:
        return None
    # 解析JSON数据
    data = json.loads(response.text)
    errcode = data.get('errcode')
    if errcode != '0':
        logging.warning('获取开盘啦热点板块数据错误 errorcode:' + errcode)
        return None
    list = data.get('list')
    date = data.get('date')
    result_map = {}
    result_map[date] = list
    #result_json = json.dumps(result_map)
    return result_map

def  getLimitUpDataListToFrom(key,list):
    '''
    板块轮动
    :param list:
    :return:
    '''
    if list is None:
        return
    plate_data_all = pd.DataFrame()
    title = '股票名称'
    if key is not None and len(key)>0:
        title = key
    for bankuai in list:
        ZSName = bankuai.get('ZSName')
        #StockList = bankuai.get('StockList')
        num = bankuai.get('num')
        ZSPop = bankuai.get('ZSPop')
        item_data = None
        if ZSPop is None or ZSPop==0:
            item_data = [
                ZSName + '[' + str(num) + ']',
            ]
        else:
            item_data = [
                ZSName+'['+str(num)+'] - '+str(ZSPop),
            ]
        # 将数据转换成DataFrame类型
        data = pd.DataFrame(item_data).T
        dict = {0: title}
        data.rename(columns=dict, inplace=True)
        plate_data_all = plate_data_all._append(data, ignore_index=True)
    return plate_data_all

def getLimitUpDataListToFromSub(list,codeName,sin):
    '''
    板块轮动-板块下个股
    :param list:
    :param codeName:
    :return:
    '''
    if list is None or codeName is None:
        return
    plate_data_all = pd.DataFrame()
    for bankuai in list:
        ZSName = bankuai.get('ZSName')
        if ZSName.find(codeName) == -1:
            continue
        StockList = bankuai.get('StockList')
        if StockList is None or len(StockList)<=0:
            continue
        for item in StockList:
            text = '涨停'
            if sin:
                item_data = [
                    item[0],
                    item[1],
                    item[9],
                    #item[17]
                ]
            else:
                text = '涨幅'
                item_data = [
                    item[0],
                    item[1],
                    item[4][:-1],
                    #item[17]
                ]
            # 将数据转换成DataFrame类型
            data = pd.DataFrame(item_data).T
            dict = {0: '股票代码',1: '股票名称',2: text}
            data.rename(columns=dict, inplace=True)
            plate_data_all = plate_data_all._append(data, ignore_index=True)
    return plate_data_all

def geteverydayReplay(list):
    '''每日复盘'''
    if list is None:
        return
    plate_data_all = pd.DataFrame()
    dict = {0: '股票代码', 1: '股票名称', 2: '涨停时间',3:'状态',4:'实际流通',5:'主板',6:'板块',7:'开板',8:'封单',9:'主力净额',10:'成交额',11:'实际换手',12:'备注',13:'板数'}
    for fp in list:
        ZSCode = fp.get('ZSCode')
        ZSName =  fp.get('ZSName')
        StockList = fp.get('StockList')
        if StockList is None or len(StockList)<=0:
            continue
        item_data = [
            '',
            ZSName,
            '','','','','','','','','','','','',
        ]
        # 将数据转换成DataFrame类型
        data = pd.DataFrame(item_data).T
        data.rename(columns=dict, inplace=True)
        plate_data_all = plate_data_all._append(data, ignore_index=True)
        for item in StockList:
            time = datetime.fromtimestamp(item[6]).strftime('%H:%M:%S')
            kb = '是' if item[18] == 1 else '否'
            sjlt = str(round(item[15] / 100000000, 2)) + '亿'
            fd = str(round(item[8] / 100000000, 2)) + '亿'
            zlje = str(round(item[12] / 10000, 2)) + '万'
            cje = str(round(item[13] / 10000, 2)) + '万'
            sjhs = str(item[14]) + '%'
            item_data_sub = [
                item[0],
                item[1],
                time, item[9], sjlt,ZSName, item[11], kb, fd, zlje, cje, sjhs,item[17],item[7]
            ]
            # 将数据转换成DataFrame类型
            data_sub = pd.DataFrame(item_data_sub).T
            data_sub.rename(columns=dict, inplace=True)
            plate_data_all = plate_data_all._append(data_sub, ignore_index=True)
    return plate_data_all


if __name__ == '__main__':
    name_list= ['锂电池:粤桂股份8','并购重组:佛塑科技5','机器人概念:东方精工5','汽车零部件(轮胎):S佳通   4',
           '消费电子:国光电器4','股权转让:海宁皮城4,化工:渤海化学4','股权转让:大千生态12'];
    #name_list = sorted(name_list, key=lambda item: (-int(item.split(':')[1][-1]), item.split(':')[0]))
    print('股权转让:大千生态12'.split(':')[1])
    print(''.join(re.findall(r'\d+','股权转让:大千生态12'.split(':')[1])))
    print(-int(''.join(re.findall(r'\d+','股权转让:大千生态12'.split(':')[1]))))
